package com.cqie.rbac.util;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cqie.rbac.entity.Dict;
import com.cqie.rbac.entity.Quota;
import com.cqie.rbac.entity.QuotaOptions;
import com.cqie.rbac.mapper.DictMapper;
import com.cqie.rbac.mapper.QuotaMapper;
import com.cqie.rbac.mapper.QuotaOptionsMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Author 夏兵
 * @Date 2021/10/13
 */
@Component
public class DynamicListener extends AnalysisEventListener<Object> {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private QuotaMapper quotaMapper;

    @Autowired
    private QuotaOptionsMapper quotaOptionsMapper;

    /**
     * 所有的行数据
     */
    private final List<Map<Integer, String>> data = new ArrayList<>();

    /**
     * 当前行所属字典id
     */
    private int dictId;

    /**
     * 储存每个一级指标下的指标id包括一级指标
     */
    private final Map<Integer, Long> parentIdMap = new HashMap<>();

    /**
     * 指标排序
     */
    private int sortCode;

    /**
     * 指标下面含有的指标选项
     */
    private final List<Long> hasOption = new ArrayList<>();

    /**
     * 分数40 30 20 10
     */
    private int scoreOption = 4;

    /**
     * 保存指标选项, 直接批量插入
     */
    private final List<QuotaOptions> quotaOptions = new ArrayList<>();

    @Override
    public void invoke(Object o, AnalysisContext analysisContext) {
        System.out.println(o);
        data.add((LinkedHashMap<Integer, String>) o);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        long parent = 0;
        for (Map<Integer, String> row : data) {
            int keyPosition = findFirstKeyPosition(row);
            if (0 == keyPosition) {
                saveDict(row.get(0));
                parentIdMap.clear();
                int num = row.size() / 2;
                for (int i = 0; i < num; i++) {
                    parent = saveQuota(row.get(i * 2), Float.parseFloat(row.get(i * 2 + 1)), parent);
                    parentIdMap.put(i, parent);
                }
            } else {
                if (keyPosition != row.size() - 1) {
                    int num = (row.size() - keyPosition - 1) / 2;
                    for (int i = 0; i < num; i++) {
                        parent = saveQuota(row.get(i * 2 + keyPosition), Float.parseFloat(row.get(i * 2 + keyPosition + 1)),
                                parentIdMap.get((2 * i + keyPosition) / 2 - 1));
                        parentIdMap.put((2 * i + keyPosition) / 2, parent);
                    }
                }
            }
            saveOptions(row.get(row.size() - 1), parent);
        }
        quotaOptionsMapper.insertBatchOption(quotaOptions);
        Quota quota = new Quota();
        quota.setHasOption(1);
        for (long tag : hasOption) {
            quota.setId((int) tag);
            quotaMapper.updateById(quota);
        }
    }

    /**
     * 查询map中第一个value不为空的key的位置
     *
     * @param map 查询的map
     * @return 所在的位置
     */
    public int findFirstKeyPosition(Map<Integer, String> map) {
        int count = 0;
        for (String value : map.values()) {
            if (StringUtils.isBlank(value)) {
                count++;
            } else {
                break;
            }
        }
        return count;
    }

    /**
     * 保存字典字段
     *
     * @param name 字典名
     */
    public void saveDict(String name) {
        Dict dict = new Dict();
        dict.setName(name);
        dictMapper.insert(dict);
        this.dictId = dict.getId();
        sortCode = 1;
    }

    /**
     * 储存指标
     *
     * @param name   指标名
     * @param weight 指标权重
     * @param parent 父节点id
     * @return 保存后的id
     */
    public long saveQuota(String name, float weight, long parent) {
        Quota quota = new Quota();
        quota.setQuotaName(name);
        quota.setWeight(weight);
        quota.setDictId((long) dictId);
        quota.setParentId(parent);
        quota.setSortCode(sortCode++);
        quotaMapper.insert(quota);
        return quota.getId();
    }

    /**
     * 保存指标选项
     *
     * @param name    选项内容
     * @param quotaId 指标id
     */
    public void saveOptions(String name, long quotaId) {
        QuotaOptions quotaOptions = new QuotaOptions();
        if (scoreOption < 1) {
            scoreOption = 4;
        }
        float score = 10 * scoreOption--;
        quotaOptions.setOptionScore(score);
        quotaOptions.setOptionName(name);
        quotaOptions.setQuotaId(quotaId);
        hasOption.add(quotaId);
        this.quotaOptions.add(quotaOptions);
    }
}
